package controllers

import (
	"animalss/cache"
	"animalss/models"
	"animalss/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserControllers struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"Code"`
	Msg  string      `json:"Msg"`
	Data interface{} `json:"Data"`
}

func (c *UserControllers) Login() {

	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "参数为空",
			Data: nil,
		}
		c.ServeJSON()
	}
	var user models.User
	models.DB.Where("username =?", username).Find(&user)
	if user.ID == 0 {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "用户名为空",
			Data: nil,
		}
		c.ServeJSON()
	}

	key := "user_login_error"
	errCount, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if errCount >= 3 {
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "密码错误,封禁两小时",
			Data: nil,
		}
		c.ServeJSON()
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if errCount == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code: 400,
			Msg:  "登陆失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	c.ServeJSON()

}
